'use strict';
const Koa = require('koa');
const fs = require('fs');
const router = require('koa-router')();
const bodyParser = require("koa-bodyparser");
const app = new Koa();

//包装路径文件函数
function addfiles(){
//获取路径下所有文件
var files = fs.readdirSync(__dirname);
//过滤出js文件
var js_files = files.filter((f) => {
    return f.endsWith('.js');
});
//调用下一个函数
    addmapping(js_files);
};

function addmapping(js_files){
//处理js_files数组内的文件
for (var f of js_files) {
    
    //文件映射
    let mapping = require(__dirname + '/' + f);

    for (var url in mapping) {

        if (url.startsWith('get')) {
            //找到get获取
            //去除get标识，显示正确路径
            let path = url.substring(4);
            //router.get
            router.get(path,mapping[url]);
        } else if (url.startsWith('post')) {
            //找到post传输
            //去除post标识，显示正确路径
            let path = url.substring(5);
            //router.post
            router.post(path,mapping[url]);
        } else {
            //无效路径
            console.log(url);
        }
    }
};
}

module.exports=function(listen){
    addfiles();
    
    return {
        bodyParser:app.use(bodyParser()),
        router:app.use(router.routes()),
        listen:app.listen(listen)
    }
};






